library(survey)
library(dplyr)
library(ggplot2)
library(gridExtra)

# Figure 8.8
summary(factor(df$Q11T))
summary(factor(df$Q4D))
summary(factor(df$Q4AD))

df$Q4D2 <- NA
df$Q4D2[df$Q4D < 77] <- 0.5
df$Q4D2[df$Q4D < 3] <- 1
df$Q4D2[df$Q4D > 3 & df$Q4D < 77] <- 0

df$Q4AD2 <- NA
df$Q4AD2[df$Q4AD < 77] <- 0.5
df$Q4AD2[df$Q4AD < 3] <- 1
df$Q4AD2[df$Q4AD > 3 & df$Q4AD < 77] <- 0

df_Q4D2 <- df[!is.na(df$Q4D2) & df$Q11 < 77 & !is.na(df$party),]
df_Q4AD2 <- df[!is.na(df$Q4AD2) & df$Q11 < 77 & !is.na(df$party),]

# Create Survey design
w2_design_a <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df_Q4D2
  )

w2_design_ad <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df_Q4AD2
  )

fig88_Q4D2_means <- svyby(~ Q4D2, ~ Q11T+party, w2_design_a, svymean, na.rm = TRUE)
fig88_Q4AD2_means <- svyby(~ Q4AD2, ~ Q11T+party, w2_design_ad, svymean, na.rm = TRUE)


g.D2 <- ggplot(fig88_Q4D2_means,aes(x=factor(party),y=Q4D2,fill=factor(Q11T),label=round(Q4D2,digits=2)))+
  geom_col(position = position_dodge())+
  geom_text(size=3,position=position_dodge(1),vjust=-.5)+
  ylim(0,1)+
  theme(legend.position = "null")+
  scale_x_discrete(labels=c("Democrat", 'Independent', "Republican"))+
  xlab("")+
  ylab("Mean Support for Cutting State to Fund DoD")

g.AD2 <- ggplot(fig88_Q4AD2_means,aes(x=factor(party),y=Q4AD2,fill=factor(Q11T),label=round(Q4AD2,digits=2)))+
  geom_col(position = position_dodge())+
  geom_text(size=3,position=position_dodge(1),vjust=-.5)+
  ylim(0,1)+
  scale_fill_discrete(name="Confidence\nin Military",
                    breaks=c(0,1),
                    labels=c("Not Confident","Confident"))+
  scale_x_discrete(labels=c("Democrat", 'Independent', "Republican"))+
  xlab("")+
  ylab("Mean Support for Cutting DoD to Fund State")

grid.arrange(g.D2,g.AD2,ncol=2,widths=c(1,1.2))
